package org.file5.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.file5.domain.Person;
import org.file5.service.ServiceFascade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.WebUtils;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;

public class LogonInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	private ServiceFascade sf;
	@Autowired
	private UserService googleUserService;
	private String SESSION_PERSON = "SESSION_PERSON";

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		Person person = (Person) WebUtils.getSessionAttribute(request, SESSION_PERSON);
		if (person == null) {
			User googleUser = googleUserService.getCurrentUser();
			String personUid = sf.getPersonService().getPersonUid(googleUser);
			person = sf.getPersonService().find(personUid);
			WebUtils.setSessionAttribute(request, SESSION_PERSON, person);
		}

		return true;

	}
}